package com.wedo.mall.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.e.library.adapter.EAdapter;
import com.wedo.mall.R;

import java.util.List;

/**
 * Created by lxy on 2016/9/8 16:43.
 */
public class PhotoAdapter extends EAdapter<String> {

    private final int DEFAULT_SIZE = 9;
    private int maxSize = DEFAULT_SIZE;

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

    public PhotoAdapter(Context context, List<String> datas) {
        super(context, datas);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    protected int layout() {
        return R.layout.item_photo;
    }

    @Override
    public int getItemCount() {
        if (mDatas == null) {
            return 1;
        } else if (mDatas.size() == maxSize) {
            return maxSize;
        } else {
            return mDatas.size() + 1;
        }
    }

    /**
     * 是否添加一张图片
     * @param position
     * @return
     */
    private boolean isAddItem(int position) {
        if (mDatas.isEmpty()){
            return true;
        }else if (mDatas.size() < maxSize){
            return position == mDatas.size();
        }
        else if (mDatas.size() == maxSize){
            return false;
        }
        return false;
    }

    @Override
    public EHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new EHolder(LayoutInflater.from(mContext).inflate(layout(),null));
    }

    @Override
    public void onBindViewHolder(EHolder holder, int position) {
        if (isAddItem(position)){
            ImageView iv_photo = holder.find(R.id.iv_photo);
            View v_delete = holder.find(R.id.v_delete);
            v_delete.setVisibility(View.INVISIBLE);
            v_delete.setOnClickListener(null);
            Glide.with(mContext).fromResource().load(R.drawable.picture_add).into(iv_photo);
            onBindItemClickListener(holder.itemView,null,position);

        }else {
            String data = mDatas.get(position);
            onBindData(holder,data,position);
            onBindItemClickListener(holder.itemView,data,position);
        }
    }

    private void onBindData(EHolder holder, final String data, int position) {

        ImageView iv_photo = holder.find(R.id.iv_photo);
        View v_delete = holder.find(R.id.v_delete);
        v_delete.setVisibility(View.VISIBLE);
        Glide.with(mContext).fromString().load(data).into(iv_photo);
        v_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                remove(data);
            }
        });
    }
}
